package jupitermouse.site.sink.office.kafka;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;

import java.util.stream.Stream;

import static org.apache.kafka.common.requests.DeleteAclsResponse.log;

public class KafkaSinkApp {


    public static void main(String[] args) throws Exception {

        //获取参数
        int port = 9999;
        try {
            ParameterTool tool = ParameterTool.fromArgs(args);
            port = tool.getInt("port");
        } catch (Exception e) {
            log.info("参数未设置，默认为9999");
        }

        //获取环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //读取数据
        DataStreamSource<String> source = env.socketTextStream("localhost", port);

        //转换操作
        SingleOutputStreamOperator<Tuple2<String, Long>> operator = source.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] values = value.toLowerCase().split(" ");
                Stream.of(values)
                        .forEach(item -> {
                            collector.collect(new Tuple2<>(item, 1L));
                        });
            }
        }).keyBy(0)
                .timeWindow(Time.seconds(5))
                .sum(1);
        operator.print().setParallelism(1);
        operator.map(m -> m.f0 + ":" + m.f1).addSink(sink2Kafka());

        env.execute("StreamingWCJavaApp");
    }

    /**
     * 写入Kafka
     */
    private static FlinkKafkaProducer<String> sink2Kafka() {
        FlinkKafkaProducer<String> myProducer = new FlinkKafkaProducer<String>(
                "192.168.81.130:9092",
                "kafka-sink",
                new SimpleStringSchema());

        myProducer.setWriteTimestampToKafka(true);

        return myProducer;
    }

}
